const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const cors = require('cors');
const favicon = require('serve-favicon')

// 引入路由
let indexRouter = require('./routers/index');

let app = express();

// view engine setup
// 设置ejs模板引擎
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'ejs');

// 跨域中间件
app.use(cors());

// favicon中间件
// app.use(favicon(path.join(__dirname,'../xiao_u_render/favicon.ico')))

// post接参中间件
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// cookie中间件
app.use(cookieParser());

// 资源静态化
app.use('/public', express.static(path.join(__dirname, 'public')));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// 使用路由
for (const key in indexRouter) {
  app.use('/api', indexRouter[key]);
}

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  res.send({ code: 404, msg: err });
});

// error handler
app.use(function (err, req, res, next) {
  res.send({ code: 0, msg: err ,data:null });
});

module.exports = app;
